package com.icetech.eom.service.ws.cust;

import com.icetech.commonbase.JsonTools;
import com.icetech.eom.domain.request.UserLoginRequest;
import com.icetech.eom.domain.request.UserRegisterRequest;
import com.icetech.eom.domain.response.UserLoginResponse;
import com.icetech.eom.domain.response.VersionResponse;
import com.icetech.eom.domain.response.WebServiceResponse;
import com.icetech.eom.common.constant.SecurityConstant;
import com.icetech.eom.common.constant.UserTypeEnum;
import com.icetech.eom.domain.sys.User;
import com.icetech.eom.domain.tx.UImei;
import com.icetech.eom.domain.tx.Version;
import com.icetech.eom.config.redis.RedisUtils;
import com.icetech.eom.service.tx.IUImeiService;
import com.icetech.eom.service.tx.IUserService;
import com.icetech.eom.service.tx.IVersionService;
import com.icetech.eom.common.utils.RedisTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

/**
 * 登录服务接口实现类
 * @author wangzw
 */
@Slf4j
@Component
public class SpringLoginServer {
    private static Md5PasswordEncoder md5encoder = new Md5PasswordEncoder();
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private IUImeiService iuImeiService;
    @Autowired
    private RedisTokenUtil redisTokenUtil;
    @Autowired
    private IVersionService versionService;

    @Transactional(rollbackFor = Exception.class)
    public String register(String para) {
        log.info("<注册用户> 参数:{}",para);
        WebServiceResponse webServiceResponse = new WebServiceResponse();
        UserRegisterRequest userRegisterRequest = JsonTools.toBean(para,UserRegisterRequest.class);
        //判断该用户是否已经注册
        User userByDB = userService.findByUsername(userRegisterRequest.getMobileno());
        //该用户已经注册
        if (Objects.nonNull(userByDB)){
            webServiceResponse.setState(2+"");
            webServiceResponse.setRetmsg("该用户已经注册");
            return JsonTools.toString(webServiceResponse);
        }
        //验证码验证
        Object code = redisUtils.get(SecurityConstant.WS_MSG_PRE + userRegisterRequest.getMobileno());
        if (Objects.isNull(code) || !code.toString().equals(userRegisterRequest.getVdsms())){
            webServiceResponse.setState(3+"");
            webServiceResponse.setRetmsg(" 校验码失效");
            return JsonTools.toString(webServiceResponse);
        }
        //注册用户
        User user = new User();
        user.setUserName(userRegisterRequest.getUname());
        user.setPwd(md5encoder.encodePassword(userRegisterRequest.getPwd(),""));
        user.setUserType(UserTypeEnum.register.getType());
        user.setMobileNo(userRegisterRequest.getMobileno());
        user.setEmail(userRegisterRequest.getEmail());
        user.setCompName(userRegisterRequest.getCompname());
        user.setVdSms(userRegisterRequest.getVdsms());
        user.setVdTime(new Date());
        user.setImei(userRegisterRequest.getImei());
        user.setIsEnabled(true);
        user.setIsSystem(false);
        user.setCreator("admin");
        user.setModifier("");
        user.setModifyTime(new Date());
        userService.save(user);

        //用户设备关联表
        UImei uImei = new UImei();
        uImei.setUserId(user.getId());
        uImei.setImei(userRegisterRequest.getImei());
        uImei.setApType(userRegisterRequest.getApType());
        uImei.setIsEnabled(true);
        uImei.setIsSystem(false);
        uImei.setCreator("admin");
        uImei.setOrgId(0L);
        iuImeiService.save(uImei);
        webServiceResponse.setState(0+"");
        webServiceResponse.setRetmsg("");
        return JsonTools.toString(webServiceResponse);
    }

    @Transactional(rollbackFor = Exception.class)
    public String login(String para) {
        log.info("<用户登录接口> 参数:{}",para);
        UserLoginResponse userLoginResponse = new UserLoginResponse();
        UserLoginRequest userLoginRequest = JsonTools.toBean(para, UserLoginRequest.class);
        User user = userService.findClientByUsername(userLoginRequest.getMobileno());
        if (Objects.isNull(user)){
            userLoginResponse.setState(1+"");
            userLoginResponse.setRetmsg("账号错误");
            return JsonTools.toString(userLoginResponse);
        }

        if (!user.getIsEnabled()){
            userLoginResponse.setState(4+"");
            userLoginResponse.setRetmsg("账号冻结");
            return JsonTools.toString(userLoginResponse);
        }
        if (!user.getPwd().equals(md5encoder.encodePassword(userLoginRequest.getPwd(),""))){
            userLoginResponse.setState(2+"");
            userLoginResponse.setRetmsg("账号/密码错误");
            return JsonTools.toString(userLoginResponse);
        }
        String imei;
        if (StringUtils.isBlank(user.getImei())){
            imei = "PC";
        } else {
            imei = user.getImei();
        }
        //生成令牌
        String token = redisTokenUtil.createToken(user.getMobileNo()+":"+ imei);
        //添加关联信息 用户设备
        UImei uImei = iuImeiService.selectByUserIdAndImei(user.getId(),userLoginRequest.getImei());
        if (Objects.isNull(uImei)){
            //添加
            UImei newuImei = new UImei();
            newuImei.setUserId(user.getId());
            newuImei.setImei(userLoginRequest.getImei());
            newuImei.setIsEnabled(true);
            newuImei.setIsSystem(false);
            newuImei.setCreator("admin");
            newuImei.setToken(token);
            newuImei.setApType(userLoginRequest.getApType());
            iuImeiService.save(newuImei);
        }else {
            //更新
            uImei.setToken(token);
            iuImeiService.updateByUserIdAndImei(uImei);
        }
        userLoginResponse.setState(0+"");
        userLoginResponse.setToken(token);
        userLoginResponse.setUserid(user.getId()+"");
        userLoginResponse.setUname(user.getUserName());
        userLoginResponse.setEmail(user.getEmail());
        userLoginResponse.setCompname(user.getCompName());
        log.info("<用户登录接口>,用户名:{},token:{}",user.getMobileNo(),token);
        return JsonTools.toString(userLoginResponse);
    }

    @Transactional(rollbackFor = Exception.class)
    public String changePwd(String para) throws JSONException {
        log.info("<修改密码> 参数:{}",para);
        WebServiceResponse webServiceResponse = new WebServiceResponse();
        JSONObject jsonObject = new JSONObject(para);
        String mobileno = jsonObject.get("mobileno").toString();
        String vdsms = jsonObject.get("vdsms").toString();
        String pwd = jsonObject.get("pwd").toString();
        User user = userService.findByUsername(mobileno);
        if (Objects.isNull(user)){
            webServiceResponse.setState(1+"");
            webServiceResponse.setRetmsg("账号错误");
            return JsonTools.toString(webServiceResponse);
        }
        if (!user.getIsEnabled()){
            webServiceResponse.setState(4+"");
            webServiceResponse.setRetmsg("账号冻结");
            return JsonTools.toString(webServiceResponse);
        }
        //获取当前验证码
        Object code = redisUtils.get(SecurityConstant.WS_MSG_PRE + mobileno);
        if (Objects.isNull(code) || !code.toString().equals(vdsms)){
            webServiceResponse.setState(3+"");
            webServiceResponse.setRetmsg("非原手机登录，校验码不对或超时");
            return JsonTools.toString(webServiceResponse);
        }
        //进行密码修改操作
        user.setPwd(md5encoder.encodePassword(pwd,""));
        userService.updateById(user);
        webServiceResponse.setState(0+"");
        return JsonTools.toString(webServiceResponse);
    }

    @Transactional(rollbackFor = Exception.class)
    public String updateUser(String para) throws JSONException {
        log.info("<更新用户> 参数:{}",para);
        WebServiceResponse webServiceResponse = new WebServiceResponse();
        JSONObject jsonObject = new JSONObject(para);
        String userid = (String) jsonObject.get("userid");
        String uname = jsonObject.get("uname").toString();
        String email = jsonObject.get("email").toString();
        String compname = jsonObject.get("compname").toString();
        //查看用户是否存在
        User user = userService.getById(Long.valueOf(userid));
        if (Objects.isNull(user)){
            webServiceResponse.setState(-1+"");
            webServiceResponse.setRetmsg("用户不存在");
            return JsonTools.toString(webServiceResponse);
        }
        user.setCompName(compname);
        user.setUserName(uname);
        user.setEmail(email);
        userService.updateById(user);
        webServiceResponse.setState(0+"");
        return JsonTools.toString(webServiceResponse);
    }

    /**
     * 获取版本信息
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String getVerion(){
        log.info("<获取版本> 参数:{}","");
        //获取版本信息
        Version version = versionService.selectLastVersion();
        if (Objects.isNull(version)) return "";
        VersionResponse versionResponse = new VersionResponse();
        versionResponse.setAdr_ver(version.getAdrVer());
        versionResponse.setAdr_url(version.getAdrUrl());
        versionResponse.setPc_ver(version.getPcVer());
        versionResponse.setPc_url(version.getPcUrl());
        versionResponse.setIos_ver(version.getIosVer());
        versionResponse.setIos_url(version.getIosUrl());
        return JsonTools.toString(versionResponse);
    }
}
